package api;

import cn.hutool.core.util.JNDIUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Article;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/artdetail")
public class ArtDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Article article = new Article();
        String msg = "未知错误！";
        // 1. 得到前端的参数并校验
        String aidStr = req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)) {
            // 2.查询数据库并获取文章详情
            Connection connection = DBUtils.getConnection();
            String sql = "select * from article where aid=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, Integer.valueOf(aidStr));
            ResultSet resultSet = statement.executeQuery();
            if(resultSet.next()) {
                article.setAid(resultSet.getInt("aid"));
                article.setTitle(resultSet.getString("title"));
                article.setContext(resultSet.getString("context"));
                String ctime = resultSet.getString("createtime");
                article.setCreatetime(ctime.substring(0, ctime.lastIndexOf(".")));
                article.setReadcount(resultSet.getInt("readcount"));
            }
            // 关闭资源
            DBUtils.close(resultSet, statement, connection);
        } else {
            msg = "参数错误！";
        }
        // 3. 将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,article,msg)));
    }
}














